import { RouteRecordRaw } from "vue-router";
let firstPath = "";

// 根据后端返回的当前用户的权限菜单，匹配对于当前用户应当注册的路由对象
export function mapMunuToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];
  // 保存所有的路由对象
  const allRoutes: RouteRecordRaw[] = [];
  // 拿到router/main文件夹下的所有ts文件
  const routeFile = require.context("../router/main", true, /\.ts/);
  // keys()方法可以拿到router/main文件夹下的所有ts文件的路径组成的字符串数组(路径是相对于router/main的)
  routeFile.keys().forEach((key) => {
    // 拿到文件导出的内容，也就是一个个的路由对象
    const route = require("../router/main" + key.split(".")[1]);
    allRoutes.push(route.default);
  });

  // 根据菜单拿到对应的路由对象
  getRoutes(userMenus);
  function getRoutes(userMenus: any[]) {
    for (const menu of userMenus) {
      if (menu.type === 2) {
        const route = allRoutes.find((item) => item.path === menu.url);
        if (route) routes.push(route);
        // 获得第一个匹配的路径
        if (firstPath.length === 0) {
          firstPath = menu.url;
        }
      } else if (menu.type === 1) {
        getRoutes(menu.children);
      }
    }
  }
  return routes;
}

export function mapPathToBreadcrumb(userMenus: any[], path: string): any {
  const breadcrumbArr = [];
  for (const menu of userMenus) {
    if (menu.type === 1) {
      if (path.includes(menu.url)) {
        breadcrumbArr.push({ name: menu.name }); //一级路由
        breadcrumbArr.push(mapPathToBreadcrumb(menu.children, path)); //二级路由
      }
    } else if (menu.type === 2) {
      if (path === menu.url) {
        return { name: menu.name, path: menu.url };
      }
    }
  }
  return breadcrumbArr;
}

export function mapMenuToPermission(userMenus: any[]) {
  const permission: string[] = [];
  function getPermissions(userMenus: any[]) {
    for (const menu of userMenus) {
      if (menu.type === 1 || menu.type === 2) {
        getPermissions(menu.children ?? []);
      } else if (menu.type === 3) {
        permission.push(menu.permission);
      }
    }
  }
  getPermissions(userMenus);
  return permission;
}

export function mapMenuToLeafNodeKeys(menuList: any[]) {
  const leafNodeKeys: number[] = [];
  const getLeafNodeKeys = (list: any[]) => {
    for (const item of list) {
      if (item.children) {
        getLeafNodeKeys(item.children);
      } else {
        leafNodeKeys.push(item.id);
      }
    }
  };
  getLeafNodeKeys(menuList);
  return leafNodeKeys;
}

export { firstPath };
